【Android TimeCat】 当RxJava遇到Retrofit(二)api注解@Path, @Url等
背景
下面分为GET
、POST
、DELETE
还有PUT
的请求,说明@Path
、@Query
、@QueryMap
、@Body
、@Field
的用法。
初始化Retrofit
1 | String BASE_URL = "http://192.168.88.105:8000/api/"; |
GET
样式1(一个简单的get请求)
http://192.168.88.105:8000/api/News1
2"News") (
Call<NewsBean> getItem();
样式2(URL中有参数)
http://192.168.88.105:8000/api/News/1
http://192.168.88.105:8000/api/News/{资讯id}1
2
3
"News/{newsId}") (
Call<NewsBean> getItem(@Path("newsId") String newsId);
或
http://192.168.88.105:8000/api/News/1/类型1
http://192.168.88.105:8000/api/News/{资讯id}/{类型}
1 | "News/{newsId}/{type}") ( |
样式3(参数在URL问号之后)
http://192.168.88.105:8000/api/News?newsId=1
http://192.168.88.105:8000/api/News?newsId={资讯id}
1 | "News") ( |
或
http://192.168.88.105:8000/api/News?newsId=1&type=类型1
http://192.168.88.105:8000/api/News?newsId={资讯id}&type={类型}
1 | "News") ( |
样式4(多个参数在URL问号之后,且个数不确定)
http://192.168.88.105:8000/api/News?newsId=1&type=类型1…
http://192.168.88.105:8000/api/News?newsId={资讯id}&type={类型}…
1 | "News") ( |
也可以
1 | "News") ( |
POST
样式1(需要补全URL,post的数据只有一条reason)
http://192.168.88.105:8000/api/Comments/1
http://192.168.88.105:8000/api/Comments/{newsId}
1 |
|
样式2(需要补全URL,问号后加入access_token,post的数据只有一条reason)
http://192.168.88.105:8000/api/Comments/1?access_token=1234123
http://192.168.88.105:8000/api/Comments/{newsId}?access_token={access_token}
1 |
|
样式3(需要补全URL,问号后加入access_token,post一个body(对象))
http://192.168.88.105:8000/api/Comments/1?access_token=1234123
http://192.168.88.105:8000/api/Comments/{newsId}?access_token={access_token}
1 | "Comments/{newsId}") ( |
DELETE
样式1(需要补全URL)
http://192.168.88.105:8000/api/Comments/1
http://192.168.88.105:8000/api/Comments/{commentId}
1 | "Comments/{commentId}") ( |
样式2(需要补全URL,问号后加入access_token)
http://192.168.88.105:8000/api/Comments/1?access_token=1234123
http://192.168.88.105:8000/api/Comments/{commentId}?access_token={access_token}
1 | "Comments/{commentId}") ( |
样式3(带有body)
http://192.168.88.105:8000/api/Comments
1 | "DELETE",path = "Comments",hasBody = true) (method = |
PUT(这个请求很少用到,例子就写一个)
http://192.168.88.105:8000/api/Accounts/1
http://192.168.88.105:8000/api/Accounts/{accountId}
1 | "Accounts/{accountId}") ( |
总结
- @Path:所有在网址中的参数(URL的问号前面),如:
http://192.168.88.105:8000/api/Accounts/{accountId} - @Query:URL问号后面的参数,如:
http://192.168.88.105:8000/api/Comments?access_token={access_token} - @QueryMap:相当于多个@Query
- @Field:用于POST请求,提交单个数据
- @Body:相当于多个@Field,以对象的形式提交
Tips
- Tips1 使用@Field时记得添加@FormUrlEncoded
- Tips2 若需要重新定义接口地址,可以使用@Url,将地址以参数的形式传入即可。如
1
2
3
4
5
6
Call<List<Activity>> getActivityList(
String url,
Map<String, String> map);
Call<List<Activity>> call = service.getActivityList(
"http://115.159.198.162:3001/api/ActivitySubjects", map);
参考
https://www.jianshu.com/p/7687365aa946
https://www.jianshu.com/p/6b3daeda1eed